from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, \
    CreateAPIView, UpdateAPIView, DestroyAPIView
# Create your views here.
from rest_framework.response import Response

from rest_framework_extensions.cache.mixins import \
    CacheResponseMixin

from areas import serializers
from areas.models import Area
from areas.serializers import AreasSerializer, AddressSerializers
from users.models import Address


class AreasView(CacheResponseMixin, ListAPIView):
    '''
    获取所有省的信息
    '''
    serializer_class = AreasSerializer
    # 过滤后的查询集数据
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    '''
    获取所有市的信息和区县的信息
    '''
    serializer_class = AreasSerializer

    # queryset = Area.objects.filter(parent_id=pk)

    # @ache_response(time=60*60,cache='default')
    def get_queryset(self):
        # 获取路由中的pk值
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView,UpdateAPIView,ListAPIView):
    '''

    保存地址
    '''
    serializer_class = AddressSerializers
    # queryset = Address.objects.filter()

    def get_queryset(self):
        # 修改地址
        return Address.objects.filter(user=self.request.user,is_deleted=False)

    def delete(self,request,pk):
        '''
        删除地址
        '''

        obj = self.get_object()

        obj.is_deleted = True
        obj.save()

        return Response()

    # 重写list，前端在返回时在data后面加的是addresses
    # this.addresses=response.data.addresses
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page,many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset,many=True)
        return Response({'addresses':serializer.data,
                         'default_address_id':self.request.user.default_address_id})





